const fs = require("fs");
const md5 = require("md5");
const root_path = process.argv[2];
let preveMd5 = null;
let fsWait = false;

const listenPath = "../doc/";
console.log(`正在监听 ${listenPath}`);

fs.watch(listenPath, {recursive: true}, (event, filename) => {
    if (!filename) {
        return;
    }
    if (fsWait) {
        return;
    }
    fsWait = setTimeout(() => {
        fsWait = false;
    }, 100);
    const fName = listenPath + filename;
    const existsFile = fs.existsSync(fName);
    if (!existsFile) {
        return;
    }
    fs.stat(fName, (err, data) => {
        if (err) {
            return;
        }
        if (data.isFile()) {
            let currentMd5 = md5(fs.readFileSync(fName));
            if (currentMd5 === preveMd5) {
                return;
            }
            preveMd5 = currentMd5;
            console.log(`${fName}文件发生更新`);
            handleUpdateStaticRouteJson(listenPath)
        }
    })
});

function handleUpdateStaticRouteJson(parentPath) {
    let childFiles = getAllFiles(parentPath);
    console.log(childFiles);
    let routeList = []
    childFiles.forEach((path, index) => {
        let route = {
            "name": "doc" + index,
            "path": convertPath(path),
            "component": "document/html-file/index.vue",
            "meta": {"title": getFilename(path)}
        }
        routeList.push(route)
    })

    // let data = JSON.stringify(routeList); // 单行json
    let data = JSON.stringify(routeList, null, 2); // 格式化json
    fs.writeFile("routers.json", data, (err) => {
        if (err) throw err;
        console.log("update ");
    });
}

// 获取目录下的文件列表
function getAllFiles(parentPath) {
    let fileList = [], files = fs.readdirSync(parentPath);
    files.forEach(function (file) {
        let pathname;
        if (String(parentPath).endsWith("/")) {
            pathname = parentPath + file;
        } else {
            pathname = parentPath + "/" + file;
        }
        let stat = fs.lstatSync(pathname);
        if (!stat.isDirectory()) {
            fileList.push(pathname.replace(root_path, "."));
        } else {
            fileList = fileList.concat(getAllFiles(pathname));
        }
    });
    return fileList;
}

function convertPath(path) {
    if (!path) {
        return "";
    }
    let relativePathPrefix = "\.\.";
    let s = String(path);
    if (s.startsWith(relativePathPrefix)) {
        return s.replace(relativePathPrefix, "");
    }
}

function getFilename(path) {
    if (!path) {
        return "";
    }
    let splits = path.split("/");
    return splits[splits.length - 1];

}
